package reduce.fz.com.reduce.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.util.base.FileCache;
import reduce.fz.com.reduce.util.base.ReduceApplication;

/**
 * Feel相册相关文件路径
 *
 * @auth lipf on 2015/1/12.
 */
public class ImageSaveUtil {

    //SDK根目录feel文件夹
    private final static String FEEL_IMAGE_PATH = "/feel/";

    /**
     * 对某个view截图
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromView(View v) {
        if (v == null || v.getVisibility() != View.VISIBLE || v.getWidth() == 0 || v.getHeight() == 0) {
            return null;
        }
        try{
            Bitmap screenShot;
            screenShot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(screenShot);
            c.translate(-v.getScrollX(), -v.getScrollY());
            v.draw(c);
            return screenShot;
        }catch (Throwable e){
            ReduceLog.e(e);
            return null;
        }
    }

    /**
     * 获取feel相册的绝对路径
     *
     * @param context
     * @return
     */
    public static String getImageSavePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            String path = Environment.getExternalStorageDirectory() + FEEL_IMAGE_PATH;
            File file = new File(path);
            try {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } catch (Exception e) {
                ReduceLog.e(e);
            }
            try {
                if (!file.exists()) {
                    path = FileCache.getPhotoDir(context);
                    file.mkdirs();
                }
            } catch (Exception e) {
                ReduceLog.e(e);
            }
            return path;
        } else {
            String path = null;
            File cacheDir = context.getCacheDir();
            if (cacheDir.exists()) path = cacheDir.getAbsolutePath();
            return path;
        }
    }

    /**
     * 保存bitmap图片到本地文件
     *
     * @param bitmap
     * @param filePath
     */
    public static void saveImage(Bitmap bitmap, String filePath) {
        FileOutputStream out = null;
        try {
            File file = new File(filePath);
            if(file.exists() && file.isFile()){
                return;
            } else {
                file.createNewFile();
            }
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
            }
        } catch (Exception e) {
            ReduceLog.e(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    ReduceLog.e(e);
                }

            }
        }

    }

    /**
     * 将原图保存水印图片
     * @param oldFilePath
     */
    public static void saveImageWithWatermark(String oldFilePath) {
        try{
            if( TextUtils.isEmpty(oldFilePath) ){
                return;
            }
            File f = new File(oldFilePath);
            if (!f.isFile()) {
                return;
            }
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(oldFilePath,opts);
            // Calculate inSampleSize
            opts.inSampleSize = ImageCompressUtil.calculateInSampleSize(opts, 1440, 1440);
            // Decode bitmap with inSampleSize set
            opts.inJustDecodeBounds = false;
            Bitmap bitmap = null;
            try{
                bitmap = BitmapFactory.decodeFile(oldFilePath, opts);
            } catch (OutOfMemoryError e){
                ReduceLog.e(e);
            } catch (Throwable e){
                ReduceLog.e(e);
            }
            if(bitmap == null){
                return;
            }

            int w = bitmap.getWidth();
            int h = bitmap.getHeight();

            Context context = ReduceApplication.getInstance();
            Bitmap watermark = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.feel_watermark)).getBitmap();
            int ww = watermark.getWidth();

            //需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了
            Bitmap newBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas cv = new Canvas(newBitmap);
            cv.drawBitmap(bitmap, 0, 0, null);// 在 0，0坐标开始画入src

            Matrix matrix = new Matrix();
            float scale = w * 1.0f / 10 / ww ;
            matrix.setScale(scale, scale);
            Bitmap resizeBmp = Bitmap.createBitmap(watermark,0,0,watermark.getWidth(),watermark.getHeight(),matrix,true);
            cv.drawBitmap(resizeBmp , 10 , 10 , null);// 左上角水印

            cv.save(Canvas.ALL_SAVE_FLAG);// 保存
            cv.restore();// 存储

            String savePath = getImageSavePath(context);
            String newFileName = savePath + System.currentTimeMillis()+ "_" + new Random().nextInt(1000) + ".jpg";
            saveImage(newBitmap,newFileName);

            try{
                Uri newUri = Uri.fromFile(new File(newFileName));
                //创建文件以后需要广播否则在某些情况下看不到图片，在系统相册也看不到图片
                if( newUri != null ){
                    Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE , newUri);
                    context.sendBroadcast(localIntent);
                }
            }catch (Throwable e){
                ReduceLog.e(e);
            }
        }catch (OutOfMemoryError e){
            ReduceLog.e(e);
        } catch (Throwable e){
            ReduceLog.e(e);
        }
    }
}
